/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { useState } from 'react';
import { history } from 'umi';

export interface PostMessageReturn<T> {
  go: (path: string, d?: T) => void;
  back: (path: string, d?: T, i?: number) => void;
  data: T;
}

let goFlag = false; // 跳转标记，区分历史记录是否还在
let cache: any = null;
/**
 *
 * 注意: data 格式需要为{ [key]:'实际数据' }形式，且需要保证key唯一，
 *      因此需要配置到常量文件中(/components/_utils/constants)
 */
export function usePostMessage<T>(): PostMessageReturn<T | undefined> {
  const [data] = useState<T>(cache as T);

  // 跳转指定页面
  const go = (p: string, d?: T) => {
    cache = d;
    goFlag = true;
    history.push(p);
  };

  // 返回指定页面
  const back = (p: string, d?: T, index: number = -1) => {
    cache = d;
    if (goFlag) {
      goFlag = false;
      console.log('index', index);
      history.go(index);
    } else {
      history.replace(p);
    }
  };

  return {
    go,
    back,
    data,
  };
}
